import { eventTrack, messages } from "share/common";
import React, { Component } from "react";
import "styles/home/main-charts.scss";
import { DatePicker, Popover, Spin, Button } from "antd";
import moment from "moment";
import Chart from "components/echarts";
import homeService from "containers/home/home.service";
import ChartService from "containers/home/home-comp/charts-service";
import ExampleTag from "containers/home/home-dashboard-share/example-tag";
import debounce from "lodash.debounce";
import WaterMark from "components/water-mark";
import img1 from "images/dashboard/refactor/1.png";
import img2 from "images/dashboard/refactor/2.png";
import img3 from "images/dashboard/refactor/3.png";
import img4 from "images/dashboard/refactor/4.png";
import img5 from "images/dashboard/refactor/5.png";
import menuRoute from "routes/menuRoute";
import emptyChartImg from "images/dashboard/refactor/empty-chart.png";

const { MonthPicker } = DatePicker;

class MainCharts extends Component {
  constructor(props) {
    super(props);
    this.state = {
      noMainChart: false,
      noServiceChart: false,
      time: moment(new Date()),
      dataOpen: undefined,
      chartsLoading: true,
      allData: undefined,
      documentOption: undefined,
      option1: undefined,
      option2: undefined,
    };
    this.flag = false;
    this.openDataFlag = false;
    this.getMainChartsData = debounce(this.getMainChartsData, 300);
    this.codeMap = {
      //开通报销单标记  [提单量，结单量]
      openServiceExpenseReportFlag: ["submitExpRptMthlyQtyStatistics", "approvedExpRptMthlyQtyStatistics"],
      //开通申请单标记  [提单量，结单量]
      openServiceApplicationBillFlag: ["submitAppBillMthlyQtyStatistics", "approvedAppBillMthlyQtyStatistics"],
      //开通借款单标记  [提单量，结单量]
      openServiceLoanBillFlag: ["submitLoanBillMthlyQtyStatistics", "approvedLoanBillMthlyQtyStatistics"],
      //开通对公支付单标记  [提单量，结单量]
      openServicePublicPayBillFlag: [
        "submitPublicPayBillMthlyQtyStatistics",
        "approvedPublicPayBillMthlyQtyStatistics",
      ],
    };
    this.codeNameMap = {
      openServiceExpenseReportFlag: messages("basic-1.key19") /*报销单*/,
      openServiceApplicationBillFlag: messages("basic-1.key18") /*申请单*/,
      openServiceLoanBillFlag: messages("basic-1.key20") /*借款单*/,
      openServicePublicPayBillFlag: messages("basic-1.key208") /*对公支付单*/,
      openServiceTicketFlag: messages("basic-1.key28") /*机票*/,
      openServiceHotelFlag: messages("basic-1.key30") /*酒店*/,
      openServiceTrainFlag: messages("basic-1.key32") /*火车*/,
      openServiceCarFlag: messages("basic-1.key33") /*用车*/,
    };
    this.yNameMap = {
      openServiceTicketFlag: messages("basic-1.key29") /*出票(张)*/,
      openServiceHotelFlag: messages("basic-1.key246") /*用量(间夜)*/,
      openServiceTrainFlag: messages("basic-1.key29") /*出票(张)*/,
      openServiceCarFlag: messages("basic-1.key34") /*用量(次)*/,
    };
    this.otherCodeMap = {
      //开通机票标记  [用量，主要供应商]
      openServiceTicketFlag: ["airTktUsedMthlyQtyStatistics", "airTktMasterSupplierStatistics"],
      //开通酒店标记
      openServiceHotelFlag: ["hotelUsedMthlyQtyStatistics", "hotelMasterSupplierStatistics"],
      //开通火车标记
      openServiceTrainFlag: ["trainUsedMthlyQtyStatistics", "trainMasterSupplierStatistics"],
      //开通用车标记
      openServiceCarFlag: ["carUsedMthlyQtyStatistics", "carMasterSupplierStatistics"],
    };
    this.exampleDataOpen = {
      openServiceExpenseReportFlag: true,
      openServiceApplicationBillFlag: true,
      openServiceLoanBillFlag: true,
      openServicePublicPayBillFlag: false,
      openServiceTicketFlag: true,
      openServiceHotelFlag: true,
      openServiceTrainFlag: true,
      openServiceCarFlag: true,
      openServiceCheckInvoiceFlag: true,
      openServiceOCRFlag: true,
      openServiceBWEFlag: true,
    };
    this.heliosInfoArray = [
      {
        img: img1,
        name: messages("basic-1.key247") /*差旅场景全覆盖*/,
      },
      {
        img: img2,
        name: messages("basic-1.key248") /*比价平台*/,
      },
      {
        img: img3,
        name: messages("basic-1.key249") /*强大的研发实力*/,
      },
      {
        img: img4,
        name: messages("basic-1.key250") /*对账管理*/,
      },
      {
        img: img5,
        name: messages("basic-1.key251") /*报表统计*/,
      },
    ];
  }

  componentWillMount() {}

  componentWillReceiveProps(nextProps) {
    this.checkStatus(nextProps);
  }

  componentDidMount() {
    const { onRef } = this.props;
    onRef && onRef(this);
    this.checkStatus(this.props);
  }

  checkStatus = (props) => {
    if (this.openDataFlag) return;
    if (props.openData || props.trialTenant) {
      if (!props.trialTenant) this.openDataFlag = true;
      this.setState({ dataOpen: props.openData }, this.getMainChartsData);
    }
  };

  setLoading = () => {
    this.setState({ chartsLoading: true });
  };

  getRealData = () => {
    if (this.state.dataOpen) this.getMainChartsData(true);
  };

  getMainChartsData = (force) => {
    const { trialTenant } = this.props;
    if (this.flag && !force) return;
    if (force) this.setState({ chartsLoading: true });
    const { time, dataOpen } = this.state;
    homeService
      .getApplicationData({ yearMonthFilter: moment(time).format("YYYY-MM") }, trialTenant)
      .then((res) => {
        if (res.status === 200) {
          const AllOption = this.handleAllOptions(res.data, trialTenant ? this.exampleDataOpen : dataOpen);
          if (!trialTenant) this.flag = true;
          this.setState({ allData: res.data, chartsLoading: false, ...AllOption });
        } else {
          this.setState({ chartsLoading: false });
        }
      })
      .catch(() => {
        this.setState({ chartsLoading: false });
      });
  };

  handleAllOptions = (data, dataOpen) => {
    const applicationArray = [];
    const otherArray = [];
    Object.keys(this.codeMap).forEach((key) => {
      if (dataOpen[key]) {
        applicationArray.push({
          main: data[this.codeMap[key][0]],
          sub: data[this.codeMap[key][1]],
          name: this.codeNameMap[key],
        });
      }
    });
    Object.keys(this.otherCodeMap).forEach((key) => {
      if (dataOpen[key]) {
        otherArray.push({
          main: data[this.otherCodeMap[key][0]],
          sub: data[this.otherCodeMap[key][1]],
          name: this.codeNameMap[key],
          yName: this.yNameMap[key],
        });
      }
    });
    if (applicationArray.length === 0) {
      this.setState({ noMainChart: true });
    }
    if (otherArray.length === 0) {
      this.setState({ noServiceChart: true });
    }
    const documentOption = ChartService.createOptions({ data: applicationArray, type: "bar" });
    if (otherArray.length === 2) {
      const option1 = ChartService.createOptions({
        data: [otherArray[0]],
        type: "area",
        config: { first: true, yName: otherArray[0].yName },
      });
      const option2 = ChartService.createOptions({
        data: [otherArray[1]],
        type: "area",
        config: { first: false, yName: otherArray[1].yName },
      });
      return { documentOption, option1, option2 };
    } else if (otherArray.length >= 3) {
      const option1 = ChartService.createOptions({
        data: otherArray.slice(0, 2),
        type: "area",
        config: {
          first: true,
          yName: otherArray
            .slice(0, 2)
            .map((item) => item.yName)
            .join("/"),
        },
      });
      const option2 = ChartService.createOptions({
        data: otherArray.slice(2, 4),
        type: "area",
        config: {
          first: false,
          yName: otherArray
            .slice(2, 4)
            .map((item) => item.yName)
            .join("/"),
        },
      });
      return { documentOption, option1, option2 };
    } else if (otherArray.length === 1) {
      const option1 = ChartService.createOptions({
        data: otherArray,
        type: "area",
        config: { first: true, yName: otherArray[0].yName },
      });
      this.props.hasOnly && this.props.hasOnly();
      return { documentOption, option1, option2: undefined };
    } else if (otherArray.length === 0) {
      return { documentOption, option1: undefined, option2: undefined };
    }
  };

  onOk = (e) => {
    this.setState({ time: e, chartsLoading: true }, () => {
      this.getMainChartsData(true);
    });
    eventTrack({
      category: "1218-新首页-埋点",
      action: `用户使用了【单量统计】的日期选择器，选择了${moment(e).format("YYYY-MM")}`,
      label: this.props.tenant.tenantName,
    });
  };

  disabledDate = (current) => {
    return current && current > moment().endOf("year");
  };

  render() {
    const { trialTenant, onConfirm } = this.props;
    const { chartsLoading, documentOption, option1, option2, noServiceChart, noMainChart } = this.state;
    return (
      <div
        id={"home-main-charts-guide-id"}
        className={`home-main-charts two-third-content ${option1 && !option2 ? "spatial-condition" : ""}`}
      >
        {!trialTenant && <WaterMark />}
        <Spin spinning={chartsLoading}>
          <div className={"title-and-calendar"}>
            <div className="main-chart-title">
              {messages("basic-1.key252") /*单量统计*/}
              {!trialTenant && (
                <span className="sub-title">
                  {
                    messages("basic-1.key294", {
                      arg1: moment().subtract(1, "days").format("YYYY-MM-DD"),
                    }) /*截止到{arg1}的最新数据*/
                  }
                </span>
              )}
            </div>
            <Popover
              trigger={trialTenant ? "hover" : ""}
              content={trialTenant ? messages("basic-1.key242") /*示例数据不支持选择月份*/ : ""}
            >
              <span>
                <MonthPicker
                  disabled={trialTenant || (noMainChart && noServiceChart) || chartsLoading}
                  disabledDate={(current) => current && current.valueOf() > Date.now()}
                  allowClear={false}
                  style={{ width: 102 }}
                  onChange={this.onOk}
                  value={this.state.time}
                  defaultValue={moment()}
                />
              </span>
            </Popover>
          </div>
          {!noMainChart && (
            <div className="card-chart">
              <Chart options={documentOption} height={288} />
            </div>
          )}
          {noMainChart && (
            <div className="no-main-chart">
              <div className="img-box">
                <img src={emptyChartImg} className="img" />
              </div>
              <div className="tip">{messages("basic-1.key225") /*暂无图表数据*/}</div>
            </div>
          )}
          {noServiceChart && (
            <div className="open-helios-service">
              <div className="home-title">{messages("basic-1.key254") /*服务商开通*/}</div>
              <div className="main-title">{messages("basic-1.key201") /*一站式差旅解决方案*/}</div>
              <div className="display-box">
                {this.heliosInfoArray.map((item) => {
                  return (
                    <div className="single-ad-card">
                      <div className="img-box">
                        <img src={item.img} className="img" />
                      </div>
                      <div className="name">{item.name}</div>
                    </div>
                  );
                })}
              </div>
              <div
                className="btn-box"
                onClick={() => {
                  this.context.router.push(menuRoute.getRouteItem("consumer-card-list", "key").url);
                  eventTrack({
                    category: "1218-新首页-埋点",
                    action: "由于用户无开通消费商，点击了前往开通",
                    label: this.props.tenant.tenantName,
                  });
                }}
              >
                <Button type="primary">{messages("basic-1.key204") /*前往开通*/}</Button>
              </div>
            </div>
          )}
          {option1 && option2 && !noServiceChart && (
            <div className="split-chart">
              <div className="single-chart">
                <Chart options={option1} height={288} />
              </div>
              <div className="single-chart">
                <Chart options={option2} height={288} />
              </div>
            </div>
          )}
          {option1 && !option2 && !noServiceChart && (
            <div className="split-chart">
              <div className="single-chart-full">
                <Chart options={option1} height={268} />
              </div>
            </div>
          )}
        </Spin>
        <ExampleTag show={trialTenant} onConfirm={onConfirm} />
      </div>
    );
  }
}

MainCharts.propTypes = {};

MainCharts.contextTypes = {
  router: React.PropTypes.object,
};

export default MainCharts;
